//
//  CommentTool.m
//  FreshMember
//
//  Created by qyc on 2019/4/29.
//  Copyright © 2019年 qyc. All rights reserved.
//

#import "CommentTool.h"

#import "CustomUpVersionPopView.h"

@implementation CommentTool
/**
 获取文件大小
 
 @param filePath filePath
 @return size
 */
+ (float) fileSizeAtPath:(NSString*) filePath {
    NSFileManager* manager = [NSFileManager defaultManager];
    if ([manager fileExistsAtPath:filePath]){
        return [[manager attributesOfItemAtPath:filePath error:nil] fileSize]/(1024.0*1024);
    }
    return 0;
}

/**
 倒计时按钮
 
 @param sender btn
 @param time 时间
 */
+ (void)countDownWithButton:(UIButton *)sender
                    andTime:(int) time {
    __block int timeout = time; //倒计时时间
    dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
    dispatch_source_t _timer = dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER, 0, 0,queue);
    dispatch_source_set_timer(_timer,dispatch_walltime(NULL, 0),1.0*NSEC_PER_SEC, 0); //每秒执行
    dispatch_source_set_event_handler(_timer, ^{
        if(timeout <= 0){ //倒计时结束，关闭
            dispatch_source_cancel(_timer);
            dispatch_async(dispatch_get_main_queue(), ^{
                //设置界面的按钮显示 根据自己需求设置
                [sender setTitle:@"重新获取" forState:UIControlStateNormal];
                sender.backgroundColor = UIColorFromRGB(0xffffff);
                [sender setTitleColor:UIColorFromRGB(0x6BA0ED) forState:UIControlStateNormal];
                sender.enabled = YES;
            });
        } else {
            //            int minutes = timeout / 60;
            int seconds = timeout % 60;
            NSString *strTime = [NSString stringWithFormat:@"%.2d", seconds];
            dispatch_async(dispatch_get_main_queue(), ^{
                //设置界面的按钮显示 根据自己需求设置
                //                NSLog(@"____%@",strTime);
                [sender setTitle:[NSString stringWithFormat:@"%@S",strTime] forState:UIControlStateNormal];
                sender.backgroundColor = UIColorFromRGB(0xffffff);
                [sender setTitleColor:UIColorFromRGB(0xCFCFCF) forState:UIControlStateNormal];
                sender.enabled = NO;
                
            });
            timeout--;
            
        }
    });
    dispatch_resume(_timer);
}

/**
 分享
 
 @param controll self
 @param title 标题
 @param content 描述
 @param url url
 @param img 图片
 */
- (void)presentIconShareView:(UIViewController *)controll title:(NSString *)title content:(NSString *)content url:(NSString *)url image:(UIImage *)img {
    
}

/**
 获取随机UUUI
 */
+ (NSString *)ossPicFileString {
    CFUUIDRef uuid_ref = CFUUIDCreate(NULL);
    CFStringRef uuid_string_ref= CFUUIDCreateString(NULL, uuid_ref);
    NSString *uuid = [NSString stringWithString:(__bridge NSString*)uuid_string_ref];
    CFRelease(uuid_ref);
    CFRelease(uuid_string_ref);
    
    NSDate *date = [NSDate date];
    NSDateFormatter *forMatter = [[NSDateFormatter alloc] init];
    [forMatter setDateFormat:@"yyyyMMdd"];
    NSString *dateStr = [forMatter stringFromDate:date];
    
    return [NSString stringWithFormat:@"pic/%@/%@",dateStr,[uuid lowercaseString]];
}

/**
 储存艺人搜索历史
 */
+ (void)saveActorSearchName:(NSArray *)searchNameArr {
    NSMutableArray *udArray  = [[NSMutableArray alloc] init];
    udArray = [UserDefaultHelper getMutableArrayForKey:@"historySearchArray"];
    
    if (udArray == nil || udArray.count == 0) {
        udArray = [[NSMutableArray alloc]initWithCapacity:0];
    }
    
    for (NSString *searchName in searchNameArr) {
        //判断是否已经含有该元素
        for (int i=0; i<udArray.count; i++) {
            if ([searchName isEqualToString:udArray[i]]) {
                [udArray removeObjectAtIndex:i];
                break;
            }
        }
        
        //如果已经存放有10个以上，删除第一个
        if(udArray.count >= 10) {
            [udArray removeLastObject];
            [udArray insertObject:searchName atIndex:0];
        } else {
            [udArray insertObject:searchName atIndex:0];
        }
    }
    //存入NSUserDefaults
    [UserDefaultHelper setMutableArrayForKey:udArray forKey:@"historySearchArray"];
}


/**
 版本更新
 
 @param controller 控制器
 */
+(void)upVersionViewWithController:(UIViewController *)controller {
    [[HAAppApi sharedApi] requestRiderUpVserionCompletionHandler:^(id  _Nullable successHandler) {
        NSDictionary *dicData = successHandler;
          // 是否强制更新1 是 0 否
          //非更新
          if ([dicData[@"update"] integerValue] == 0) {
              return ;
          } else if ([dicData[@"update"] integerValue] == 1){//非强制更新

              //获取服务器最新版本号
              NSString *newApiVersion = dicData[@"version"];
              newApiVersion = [newApiVersion stringByReplacingOccurrencesOfString:@"." withString:@""];
              // 当前手机版本号
              NSString *app_build = [[[NSBundle mainBundle] infoDictionary] objectForKey:@"CFBundleShortVersionString"];
              app_build = [app_build stringByReplacingOccurrencesOfString:@"." withString:@""];
              if ([newApiVersion integerValue]<= [app_build integerValue]) {
                  return;
              } else {
                  [self upVersionUIVersionDic:dicData controller:controller];
              }
          }
    } errorHandler:^(id  _Nullable errorHandler) {
        
        
    }];
}

/**
 版本更新UI
 
 @param dicData 内容
 */
+ (void)upVersionUIVersionDic:(NSDictionary *)dicData controller:(UIViewController *)controller {
    CustomUpVersionPopView *popView = [[CustomUpVersionPopView alloc]initWithPopTitle:[NSString stringWithFormat:@"V%@",dicData[@"version"]] andContent:dicData[@"version_info"] isConstraint:@""];
    popView.sureBlick = ^(){
        [[UIApplication sharedApplication] openURL:[NSURL URLWithString:dicData[@"version_url"]]];
    };
    [popView showInController:controller preferredStyle:TYAlertControllerStyleAlert backgoundTapDismissEnable:NO];
}

/**
 *  截取URL中的参数
 *
 *  @return NSMutableDictionary parameters
 */
+ (NSMutableDictionary *)getURLParameterUrl:(NSString *)url{
    
    // 查找参数
    NSRange range = [url rangeOfString:@"?"];
    if (range.location == NSNotFound) {
        return nil;
    }
    
    NSMutableDictionary *params = [NSMutableDictionary dictionary];
    
    // 截取参数
    NSString *parametersString = [url substringFromIndex:range.location + 1];
    
    // 判断参数是单个参数还是多个参数
    if ([parametersString containsString:@"&"]) {
        
        // 多个参数，分割参数
        NSArray *urlComponents = [parametersString componentsSeparatedByString:@"&"];
        
        for (NSString *keyValuePair in urlComponents) {
            // 生成Key/Value
            NSArray *pairComponents = [keyValuePair componentsSeparatedByString:@"="];
            NSString *key = [pairComponents.firstObject stringByRemovingPercentEncoding];
            NSString *value = [pairComponents.lastObject stringByRemovingPercentEncoding];
            
            //判断参数中含有链接参数情况
            if (pairComponents.count == 3) {
                value = [NSString stringWithFormat:@"%@=%@", pairComponents[1], pairComponents[2]];
                value = [value stringByRemovingPercentEncoding];
            }
            
            // Key不能为nil
            if (key == nil || value == nil) {
                continue;
            }
            
            id existValue = [params valueForKey:key];
            
            if (existValue != nil) {
                
                // 已存在的值，生成数组
                if ([existValue isKindOfClass:[NSArray class]]) {
                    // 已存在的值生成数组
                    NSMutableArray *items = [NSMutableArray arrayWithArray:existValue];
                    [items addObject:value];
                    
                    [params setValue:items forKey:key];
                } else {
                    
                    // 非数组
                    [params setValue:@[existValue, value] forKey:key];
                }
                
            } else {
                
                // 设置值
                [params setValue:value forKey:key];
            }
        }
    } else {
        // 单个参数
        
        // 生成Key/Value
        NSArray *pairComponents = [parametersString componentsSeparatedByString:@"="];
        
        // 只有一个参数，没有值
        if (pairComponents.count == 1) {
            return nil;
        }
        
        // 分隔值
        NSString *key = [pairComponents.firstObject stringByRemovingPercentEncoding];
        NSString *value = [pairComponents.lastObject stringByRemovingPercentEncoding];
        
        // Key不能为nil
        if (key == nil || value == nil) {
            return nil;
        }
        
        // 设置值
        [params setValue:value forKey:key];
    }
    
    return params;
}
@end
